package com.zzyl.service.impl;

import cn.hutool.core.date.LocalDateTimeUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zzyl.base.PageResponse;
import com.zzyl.dto.VisitDto;
import com.zzyl.entity.CountByTime;
import com.zzyl.entity.Visit;
import com.zzyl.enums.BasicEnum;
import com.zzyl.exception.BaseException;
import com.zzyl.mapper.CustomerReservationMapper;
import com.zzyl.service.CustomerReservationService;
import com.zzyl.utils.UserThreadLocal;
import com.zzyl.vo.VisitVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class CustomerReservationServiceImpl implements CustomerReservationService {

    private static final Logger log = LoggerFactory.getLogger(CustomerReservationServiceImpl.class);
    @Autowired
    CustomerReservationMapper customerReservationMapper;

    /**
     * 查询取消预约数量
     * @param userId 操作人id 通过本地线程获取
     * @return Integer count
     */
    @Override
    public Integer selectCancledReservationCount(Long userId) {
        LocalDate today = LocalDate.now();
        LocalDateTime todayStarting = today.atTime(0, 0, 0);
        Integer count = customerReservationMapper.selectCancledReservationCount(userId,todayStarting);
        return count;
    }

    /**
     * 添加预约
     * @param visitDto 传入的参数
     */
    @Override
    public void add(VisitDto visitDto) {
        Visit visit = new Visit();
        BeanUtils.copyProperties(visitDto, visit);
        visit.setStatus(0);
        visit.setCreateBy(UserThreadLocal.getUserId());
        visit.setUpdateBy(UserThreadLocal.getUserId());

        //判断该用户取消次数是否达到三次
        int count = selectCancledReservationCount(UserThreadLocal.getUserId());
        if (count >= 3) {
            throw new BaseException(BasicEnum.RESERVATION_CANCEL_COUNT_UPPER_LIMIT);
        }

        //判断该时间段预约数量是否达到上限（6次）
        List<CountByTime> countByTime = getCountByTime(LocalDateTimeUtil.toEpochMilli(visit.getTime().toLocalDate().atTime(0, 0, 0)));
        countByTime.forEach(reservation -> {
            if (reservation.getTime().equals(visit.getTime())) {
                if (reservation.getCount() >= 6) {
                    throw new BaseException(BasicEnum.RESERVATION_COUNT_UPPER_LIMIT);
                }
            }
        });

        //判断该手机号在当前时间是否有过预约
        List<Visit> selectByPhone = customerReservationMapper.getByPhone(visit.getMobile());
        selectByPhone.forEach(reservation -> {
            if (reservation.getTime().equals(visit.getTime())) {
                throw new BaseException(BasicEnum.TIME_ALREADY_RESERVATED_BY_PHONE);
            }
        });

        customerReservationMapper.add(visit);
    }

    /**
     * 分页查询预约记录
     */
    @Override
    public PageResponse<VisitVo> getByPage(Integer pageNum, Integer pageSize, Integer status) {
        Long userId = UserThreadLocal.getUserId();
        PageHelper.startPage(pageNum, pageSize);
        Page<Visit> visit = customerReservationMapper.getByPage(status, userId);
        PageResponse<VisitVo> visitVo = PageResponse.of(visit, VisitVo.class);
        return visitVo;
    }

    /**
     * 取消预约
     * @param id 预约记录id
     */
    @Override
    public void cancel(Long id) {
        Long userId = UserThreadLocal.getUserId();
        customerReservationMapper.cancel(id,userId);
    }

    /**
     * 查询当前时间段剩余预约数量
     * @param time 时间戳
     * @return CountByTime
     */
    @Override
    public List<CountByTime> getCountByTime(Long time) {
//        LocalDateTime timePar = LocalDateTime.ofInstant(Instant.ofEpochMilli(time), ZoneId.systemDefault());
        LocalDateTime timePar = LocalDateTimeUtil.of(time);
        List<CountByTime> list = customerReservationMapper.getCountByTime(timePar);
        return list;
    }
}


